package cn.billi.cloud.basic.consume.service;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserService {
  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private DiscoveryClient discoveryClient;

  @Autowired
  private EurekaClient eurekaClient;

  @Autowired
  private EurekaClientConfig clientConfig;

  private void printServices() {
    List<String> services = discoveryClient.getServices();
    if (services.isEmpty()) {
      System.out.println("null services");
    }
    for (String service : services) {
      System.out.println("service: " + service);
    }

    System.out.println("=======================================");
  }

  private int getRandom(int n) {
    // 0<= random and random < n
    Random ran = new Random();
    int random = ran.nextInt(n);
    return random;
  }

  public List<String> queryNames2() {
    printServices();
    String serviceId = "basic-service";
    List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);

    int size = instances.size();

    if (size > 0) {
      ServiceInstance instance = instances.get(0);
      int index = 0;
      if (size > 1) {
        index = getRandom(size);
        instance = instances.get(index);
        System.out.println("random index: " + index);
      }
      System.out
          .println(instance.getServiceId() + " " + instance.getHost() + ":" + instance.getPort());
      String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/home/users";
      return restTemplate.getForObject(baseUrl, List.class);
    }
    return Collections.emptyList();
  }

  public List<String> queryNames() {
    printServices();
    String serviceId = "basic-service";
    // List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);

    // ServiceInstance instance = instances.get(0);
    // System.out.println(instance.getServiceId() + " " + instance.getHost());
    // String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/home/users";
    String baseUrl = "http://basic-service/home/users";
    return restTemplate.getForObject(baseUrl, List.class);
  }
}
